/**
 *  created by lllwx
 *  Date: 2021/6/1
 *  Time: 2:37 下午
 *  Version: 1.0
 *  For: table hooks
 */
import {
  reactive,
  toRefs,
} from '@vue/composition-api';
import { usePage } from './usePage';

export function useTable(service, options) {
  const baseOptions = {
    pageSize: 10,
    border: true,
    resizable: true,
    pageOptions: {},
    pagination: true,
    height: 'auto',
    form: null,
    lazyLoad: false,
    emptyText: '暂无数据',
    hasData: true,
    align: 'left',
  };

  const tableProps = reactive({
    ...baseOptions,
    ...options,
    loading: false,
    data: undefined,
    count: 0,
  });

  const { pageLimit, resetPageLimit } = usePage(runService, tableProps.pageSize);

  const search = {
    submit: () => { pageLimit.value.pageNo = 1; runService(); },
    reset: resetPageAndForm,
  };

  // 重置 分页参数 和 表单
  function resetPageAndForm() {
    tableProps.form && tableProps.form.resetFields();
    tableProps.pagination && resetPageLimit();
  }

  async function runService() {
    const {
      loading, pagination, data, count, form,
    } = toRefs(tableProps);
    loading.value = true;
    try {
      const res = await service(pageLimit.value, form.value ? form.value.modelRef : {});
      // 总条数为0 表示 没有数据
      tableProps.hasData = !!res.total;
      if (pagination?.value) {
        data.value = res.result;
        count.value = res.total;
      } else {
        data.value = res.result;
      }
    } finally {
      loading.value = false;
    }
  }

  tableProps.lazyLoad || runService();

  return {
    search,
    tableProps,
    pageLimit,
  };
}
